/*
编写 : Hexh
时间 : 2012-6-26 15:52:09
*/
using System;
using System.Collections.Generic;
using HMIS.FrameWork.DomainBase;
using HMIS.FrameWork.Repository;
using HMIS.FrameWork.Repository.Nhb;
using HMIS.Infrastructure;
using HMIS.Infrastructure.Core.Entities;

namespace HMIS.Infrastructure.Core.Repositories.Impl
{
	/// <summary>
	///	 the repository of InfraSms
	/// </summary>
	public class InfraSmsRepositoryImpl : RepositoryNhbImpl<InfraSms>, IInfraSmsRepository
	{

		/// <summary>
		/// 判断是否已经有重复值
		/// </summary>
		/// <param name="fieldName">行名</param>
		/// <param name="fieldValue">值</param>
		/// <param name="id">ID列的值</param>
		/// <returns>True， False</returns>
		public bool IsFieldExist(string fieldName, string fieldValue, string id)
		{
			return base.IsFieldExist(fieldName, fieldValue, id, null);
		}
		
		// <summary>
		/// 判断是否已经有重复值
		/// </summary>
		/// <param name="fieldName">行名</param>
		/// <param name="fieldValue">值</param>
		/// <param name="id">ID列的值</param>
		/// <param name="where">Where 条件</param>
		/// <returns>True， False</returns>
		public bool IsFieldExistWhere(string fieldName, string fieldValue, string id, string where)
		{
			return base.IsFieldExist(fieldName, fieldValue, id, where);
		}
	
		/// <summary>
		/// 查询 InfraSms
		/// </summary>
		/// <param name="query">查询条件</param>
		/// <param name="start">分页开始</param>
		/// <param name="limit">分页大小</param>
		/// <param name="sort">排序条件</param>
		/// <param name="dir">排序方向</param>
		/// <param name="filters">筛选条件</param>
		/// <param name="total">返回记录条数</param>
		/// <returns>返回记录集</returns>
		public IList<InfraSms> GetPlist(string query, int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			
			// todo : 修改查询条件ID1 ID2
			string strQuery = string.IsNullOrEmpty(query) ? strFilter
				: "( t.ID1 = :query or t.ID2 = :query ) " 
					+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);

			// sort
			string strSort = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;

			// todo : 修改关联查询条件 OuterColumn
			string strSql = @" from InfraSms as t 
									left join fetch t.OuterColumn "
				+ (string.IsNullOrEmpty(strQuery) ? string.Empty : " where " + strQuery);

			// 查询
			var selQuery = Session.CreateQuery(@"select t " + strSql + strSort);
			var totQuery = Session.CreateQuery(@"select count(*) " + strSql.Replace(" join fetch ", " join "));

			// 设置查询条件
			if (!string.IsNullOrEmpty(query))
			{
				selQuery.SetString("query", query);
				totQuery.SetString("query", query);
			}

			// 分页
			if (limit > 0)
				selQuery.SetFirstResult(start).SetMaxResults(limit);

			// 汇总并返回
			total = totQuery.UniqueResult<long>();
			return selQuery.List<InfraSms>();
		}

		/// <summary>
		/// 发送短信，并保存记录
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public InfraSms SendSms(InfraSms entity)
		{
			int state = 0, icount = 10;
			string errMsg = "";
			do
			{
				// 发送
				string ret = HMIS.FrameWork.Common.SendSms.SendByGetRequest(entity.SendTo, entity.SmsContent);
				icount--;
				// 成功
				if (ret.IndexOf("成功") > 0)
					state = 1;
				// 需要重新登录 等待0.2S
				else if (ret.IndexOf("重新登录WAP飞信") > 0)
					System.Threading.Thread.Sleep(200);
				else
				{
					//其他未知错误
					errMsg = ret;
				}
			} while (state == 0 && icount > 0);

			//保存记录
			entity.State = state;
			entity.Description = errMsg;
			base.SaveOrUpdate(entity);
			return entity;
		}

		/// <summary>
		/// 新建发送记录
		/// </summary>
		/// <param name="itemId"></param>
		/// <param name="mobile"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		public InfraSms SendSms(string itemId, string mobile, string content)
		{
			InfraSms entity = new InfraSms
			{
				ItemId = itemId,
				SendTo = mobile,
				SmsContent = content,
				SendTime = System.DateTime.Now,
				State = 0
			};
			this.SendSms(entity);
			return entity;
		}

		/// <summary>
		/// 扫描InfraSms表State为0 待发送的短信并发送
		/// </summary>
		/// <returns></returns>
		public void ScanAndSend()
		{
			string strSql = @"select t from InfraSms as t where t.State = '0' and t.SendTime < :NOW";
			IList<InfraSms> smsList = Session.CreateQuery(strSql).
				SetDateTime("NOW", System.DateTime.Now).
				List<InfraSms>();

			foreach (InfraSms sms in smsList)
			{
				SendSms(sms);
			}
		}
	}
}
